import isEmpty from 'lodash/isEmpty';
import Util from './utils/util.js';
import { openWindow } from '@/helper';
import Icon from '@/components/icon';
import floatBtn from '@/components/floatbtn';
import Header from '@/components/header';

export default {
  data() {
    return {
      currentDate: new Date(), // 当前日期
      selectDate: new Date(), // 选中日期
      collapseDays: false, // 默认折叠
      tasks: {}, // 日程数据
      currentTasks: [], // 选中日期日程
      weekHeader: ['一', '二', '三', '四', '五', '六', '日'],
      dtPicker: {},
    };
  },
  components: { Icon, floatBtn, Header },
  computed: {
    currentMonth() {
      const y = this.currentDate.getFullYear();
      let m = this.currentDate.getMonth() + 1;
      m = m < 10 ? `0${m.toString()}` : m;
      return `${y}年${m}月`;
    },
    days() {
      return this.getDays();
    },
    showList() {
      const currentDate = JE.dateFormat(this.currentDate, 'YYYY-MM-DD');
      if (currentDate.split('-')[0] === this.selectDate.split('-')[0]
      && currentDate.split('-')[1] === this.selectDate.split('-')[1]) {
        return true;
      }
      return false;
    },
    bubbleList() {
      let list = this.currentTasks;
      const utillist = [];
      const alllist = [];
      list.forEach((item) => {
        if (this.getHour(item) === '全天') {
          alllist.push(item);
        } else {
          utillist.push(item);
        }
      });
      let i = utillist.length - 1;
      while (i > 0) {
        let pos = 0;
        for (let j = 0; j < i; j += 1) {
          // if (utillist[j].utilDate.slice(0, 2) > utillist[j + 1].utilDate.slice(0, 2)) {
          if (this.getHour(utillist[j]).slice(0, 2) > this.getHour(utillist[j + 1]).slice(0, 2)) {
            pos = j;
            // eslint-disable-next-line
            const tmp = utillist[j]; utillist[j] = utillist[j + 1]; utillist[j + 1] = tmp;
          }
        }
        i = pos;
      }
      list = [].concat(utillist).concat(alllist);
      // console.log(list);
      return list;
    },
  },
  created() {
    Waves.init();
  },
  mounted() {
    const me = this;
    // const nextpage = this.$route.query.type;
    // if (nextpage === 'refreshList') {
    //   this.refreshList();
    // }
    window.addEventListener('research', () => {
      this.$nextTick(() => {
        me.getDays();
      });
    });
    me.$nextTick(() => {
      const day = { sDate: JE.dateFormat(me.selectDate, 'YYYY-MM-DD') };
      me.selectDay(day);
      // 下拉刷新
      // me.pullrefresh = mui('#refreshContainer').pullRefresh4HTML({
      //   down: {
      //     callback() {
      //       setTimeout(() => {
      //         me.pullrefresh.endPulldownToRefresh();
      //         me.getDays();
      //       }, 1000);
      //     },
      //   },
      // });
    });
    this.dtPicker = new mui.DtPicker({
      type: 'month',
    });
  },
  methods: {
    // _initCtr() {
    //   JE.initCtr('JE.sys.calendar.controller.CalendarController');
    // },
    /**
     * 任务标记
     * @param {*} day
     */
    isTask(day) {
      return !isEmpty(this.tasks[day.sDate]);
    },
    /**
     * 选中标记
     * @param {*} day
     */
    isSelect(day) {
      const d = JE.dateFormat(this.selectDate, 'YYYY-MM-DD');
      return day.sDate === d;
    },
    /**
     * 选中周标记
     * @param {*} week
     */
    isSelectWeek(week) {
      const dayStr = JE.dateFormat(this.selectDate, 'YYYY-MM-DD');
      let select = false;
      for (let i = 0; i < week.length; i += 1) {
        if (week[i].sDate === dayStr) {
          select = true;
          break;
        }
      }
      return select;
    },
    /**
     * 选中日期
     * @param {*} day
     */
    selectDay(day) {
      // this.selectDate = Ext.Date.parse(day.sDate, 'Y-m-d');
      this.selectDate = JE.dateFormat(day.sDate, 'YYYY-MM-DD');
      this.currentTasks = this.tasks[day.sDate] || [];
      if (day.prevMonth) {
        this.prevMonth();
      } else if (day.nextMonth) {
        this.nextMonth();
      }
    },
    /**
     * 今天
     */
    today() {
      this.currentDate = new Date();
      this.selectDate = new Date();
      this.collapseDays = false;
      const me = this;
      me.$nextTick(() => {
        // 选中日期
        const day = { sDate: JE.dateFormat(me.selectDate) };
        me.selectDay(day);
      });
    },
    /**
     * 下月
     */
    nextMonth() {
      this.currentDate = this.changeMonth(this.currentDate, -1);
    },
    /**
     * 上月
     */
    prevMonth() {
      this.currentDate = this.changeMonth(this.currentDate, 1);
    },
    /**
     * 获得当前月的所有日期
     */
    getDays() {
      const year = this.currentDate.getFullYear();
      const month = this.currentDate.getMonth();
      const weeks = Util.calendarWeeks(year, month);
      this.initTasks(weeks);
      return weeks;
    },
    /**
     * 获得当前月的日程
     * @param {*} weeks
     */
    initTasks(weeks) {
      const userInfo = JE.getCurrentUser();
      const startDate = weeks[0][0].sDate;
      const endDate = weeks[weeks.length - 1][6].sDate;
      const params = {
        tableCode: 'JE_SYS_CALENDAR',
        limit: -1,
        permSql:
          `AND (SY_CREATEUSER="${userInfo.userCode}" OR CALENDAR_GROUPID IN (SELECT GROUPUSER_GROUP_ID FROM JE_SYS_GROUPUSER WHERE GROUPUSER_USERID="${userInfo.id}") OR CALENDAR_GROUPID IN (SELECT JE_SYS_CALENDARGROUP_ID FROM JE_SYS_CALENDARGROUP WHERE SY_CREATEUSER="${userInfo.userCode}"))`,
        whereSql: `AND ((CALENDAR_STARTTIME>='${startDate}' AND CALENDAR_STARTTIME<='${endDate}')  or (CALENDAR_ENDTIME>='${startDate}' AND CALENDAR_ENDTIME<='${endDate}'))`,
      };
      JE.ajax({
        url: `/je/calendar/calendar/load?_dc=${new Date().getTime()}`,
        params,
      }).then((response) => {
        if (response.rows && response.rows.length > 0) {
          const tasks = response.rows;
          const taskObj = {};
          tasks.forEach((task) => {
            const startDate = new Date(task.CALENDAR_STARTTIME.replaceAll('-', '/'));
            const endDate = new Date(task.CALENDAR_ENDTIME.replaceAll('-', '/'));
            // 计算任务周期
            const days = this.diffDays(startDate, endDate);
            // 为每一天增加任务新
            for (let i = 0; i <= days; i += 1) {
              const dateStr = JE.dateFormat(startDate, 'YYYY-MM-DD');
              taskObj[dateStr] = taskObj[dateStr] || [];
              taskObj[dateStr].push(task);
              startDate.setDate(startDate.getDate() + 1);
            }
          });
          this.tasks = taskObj;
          for (const key in this.tasks) {
            for (let i = 0; i < this.tasks[key].length; i++) {
              this.tasks[key][i].utilDate = this.getHour(this.tasks[key][i]);
            }
          }
          if (this.selectDate) {
            this.currentTasks = this.tasks[JE.dateFormat(this.selectDate, 'YYYY-MM-DD')] || [];
          }
        }
      });
    },
    goDetail(item) {
      // if (item) {
      //   Waves.attach('.task');
      // }
      const calStartTime = JE.dateFormat(new Date(this.selectDate), 'YYYY-MM-DD HH:mm:ss');
      const params = item || {
        SY_CREATEUSER: JE.getCurrentUser().userCode,
        SY_CREATEUSERNAME: JE.getCurrentUser().username,
        SY_CREATEUSERID: JE.getCurrentUser().id,
        CALENDAR_STARTTIME: calStartTime,
      };
      if (item) {
        this.$router.push({
          path: '/JE-PLUGIN-CALENDAR/calendardetail',
          query: {
            id: '__calendarDetailView',
            title: '编辑日程',
            item: params,
            type: 'edit'
          },
        });
        // openWindow({
        //   url: './pages_calendardetail_index.html',
        //   id: '__calendarDetailView',
        //   title: '编辑日程',
        //   extras: {
        //     item: params,
        //     type: 'edit',
        //   },
        //   hideNView: true,
        //   softinputMode: 'adjustResize',
        // });
      } else {
        this.$router.push({
          path: '/JE-PLUGIN-CALENDAR/calendardetail',
          query: {
            id: '__calendarDetailView',
            title: '创建日程',
            item: params,
            type: 'add'
          },
        });
        // openWindow({
        //   url: './pages_calendardetail_index.html',
        //   id: '__calendarDetailView',
        //   title: '创建日程',
        //   extras: {
        //     item: params,
        //     type: 'add',
        //   },
        //   hideNView: true,
        //   softinputMode: 'adjustResize',
        // });
      }
    },
    allSchedule() {
      Waves.attach('.float-btn', ['waves-circle']);
      const selectMonth = JE.dateFormat(this.currentDate, 'YYYY-MM');
      this.$router.push({
        path: '/JE-PLUGIN-CALENDAR/allschedule',
        query: {
          id: '__allScheduleView',
          title: '所有日程',
          selectMonth: selectMonth
        },
      });
      // openWindow({
      //   url: './pages_allschedule_index.html',
      //   id: '__allScheduleView',
      //   title: '所有日程',
      //   extras: {
      //     selectMonth,
      //   },
      // });
    },
    changeMonth(d, count) {
      const date = new Date(d);
      let y = date.getFullYear();
      let m = date.getMonth() + 1;
      if (count > 0) {
        if (m === 1 || m === '1' || m === '01') {
          y -= count;
          m = 12;
        } else {
          m -= count;
        }
      } else if (m === 12 || m === '12') {
        y -= count;
        m = 1;
      } else {
        m -= count;
      }
      m = m < 10 ? `0${m.toString()}` : m;
      return new Date(`${y}/${m}/01`);// ios兼容性用/代替-
    },
    diffDays(startTime, endTime) {
      const diff = endTime.getTime() - startTime.getTime();
      // return (diff / 1000 / 60 / 60 / 24).toFixed();
      return Math.floor(diff / 1000 / 60 / 60 / 24);
    },
    getHour(item) {
      const beginDay = item.CALENDAR_STARTTIME.split(' ')[0];
      const endDay = item.CALENDAR_ENDTIME.split(' ')[0];
      if (beginDay === endDay) {
        return `${this.gh(item.CALENDAR_STARTTIME)}点-${this.gh(item.CALENDAR_ENDTIME)}点`;
      }
      if (this.selectDate === beginDay) {
        return `${this.gh(item.CALENDAR_STARTTIME)}点开始`;
      }
      if (this.selectDate === endDay) {
        return `${this.gh(item.CALENDAR_ENDTIME)}点结束`;
      }
      if (this.selectDate !== beginDay && this.selectDate !== endDay) {
        return '全天';
      }
    },
    gh(date) {
      const time = JE.dateFormat(date).split(' ')[1];
      return time.split(':')[0];
    },
    // 点击顶部时间切换月份
    handleDateClick() {
      this.dtPicker.show(({ value }) => {
        const day = `${value.replaceAll('-', '/')}/01`;
        this.currentDate = new Date(day);
      });
    },
    shortTitle(title) {
      const maxlength = 13;
      if (title.length > maxlength) {
        return `${title.slice(0, maxlength)}...`;
      }
      return title;
    },
  },
};
